package com.freegeese.security.test.chapter2.realm;

import com.freegeese.security.test.chapter2.permission.BitPermission;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.permission.WildcardPermission;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class CustomAuthorizerRealm extends AuthorizingRealm {
    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole("role1");
        info.addRole("role2");

        info.addObjectPermission(new BitPermission("+user1+10"));
        info.addObjectPermission(new WildcardPermission("user1:*"));
        info.addStringPermission("+user2+10");
        info.addStringPermission("user2:*");

        return info;
    }

    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 主体
        String principal = String.valueOf(token.getPrincipal());
        // 凭证
        String credentials = String.valueOf((char[]) token.getCredentials());
        if (!"a".equals(principal)) {
            throw new UnknownAccountException();
        }
        if (!"1".equals(credentials)) {
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(principal, credentials, getName());
    }
}
